﻿using CWCS.BLL.WebReference;
using CWCS.Common;
using CWCS.Core.Library.SocketManager;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CWCS.BLL
{
    public class PhotoBLL
    {
        WebReference.HCService service = new WebReference.HCService();
        public static CellListForTray cellListForTray = new CellListForTray();
        public static Dictionary<string, Result> cellInfos = new Dictionary<string, Result>();
        public string PhotoUrl = ConfigurationManager.AppSettings["PhotoUrl"].ToString().Trim();
        public void Test()
        {
            service.getWmsCellListByTrayIdAsync("A", "B");
            service.getWmsCellListByTrayIdCompleted += new WebReference.getWmsCellListByTrayIdCompletedEventHandler(service_completed);
        }
        private static void service_completed(object sender, WebReference.getWmsCellListByTrayIdCompletedEventArgs e)
        {
            cellListForTray = e.Result;
        }
        public void Test1()
        {
            var wc = new WebClient();
            wc.DownloadDataAsync(new Uri(""));
            wc.DownloadDataCompleted += vc_DownloadDataCompleted;
        }
        private void vc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {

        }

        public void noticePhoto(string station, string barcode)
        {
            Task.Run(() =>
            {
                try
                {
                    CommonHelper helper = new CommonHelper();
                    string url = PhotoUrl;   // "http://192.168.9.30:50005/CaptureImage";
                    string postData = barcode;
                    bool b_Flag = false;
                    string msg = "";
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    webRequest.Method = "POST";
                    webRequest.ContentType = "application/json";
                    webRequest.ContentLength = byteArray.Length;
                    webRequest.Timeout = 20000;
                    System.IO.Stream stream = webRequest.GetRequestStream();
                    stream.Write(byteArray, 0, byteArray.Length);
                    stream.Close();
                    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                    string res = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                    if (!String.IsNullOrEmpty(res))
                    {
                        object obj = helper.Deserialize(res, typeof(QRCodeResult), ref b_Flag, ref msg);
                        if (obj is QRCodeResult)
                        {
                            QRCodeResult info = obj as QRCodeResult;
                            cellInfos[station].qRCodeResult = info;
                            cellInfos[station].flag = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    cellInfos[station].flag = true;
                    cellInfos[station].message = e.Message;
                }
            });
        }

        public bool startPhoto(string station, string barcode, ref Dictionary<int, string> cellInfo, bool again = false)
        {
            if (cellInfos.Where(x => x.Key == station).Count() == 0)  //当该站台无拍照数据
            {
                cellInfos.Add(station, new Result());//拍照前  将站台绑定的数据初始化
            }
            if (cellInfos.Where(x => x.Key == station && x.Value.flag && x.Value.barcode != barcode).Count() > 0)  //已成功拍照  但是托盘条码不是当前条码
            {
                cellInfos[station] = new Result();//拍照前  将站台绑定的数据初始化
            }
            if (cellInfos.Where(x => x.Key == station && x.Value.barcode == barcode && x.Value.flag).Count() > 0 && again) //当前托盘已拍照完成  需要再次拍照
            {
                cellInfos[station] = new Result();//拍照前  将站台绑定的数据初始化
            }
            if (cellInfos.Where(x => x.Key == station && x.Value.barcode == barcode).Count() == 0)  //当该托盘没有拍照记录
            {
                cellInfos[station].barcode = barcode;
                noticePhoto(station, barcode); //通知拍照
            }
            if (cellInfos.Where(x => x.Key == station && x.Value.barcode == barcode && x.Value.flag).Count() > 0) //拍照完成
            {
                if (cellInfos[station].qRCodeResult != null)
                {
                    cellInfo = cellInfos.Where(x => x.Key == station && x.Value.barcode == barcode && x.Value.flag).FirstOrDefault().Value.qRCodeResult.Data;
                }
                return true;
            }
            return false;
        }

        public enum ErrorType
        {
            // 成功
            Successed,
            // 相机错误  
            CameraError,
            // 存在二维码识别失败的情况
            SomeResultError,
        }
        public class QRCodeResult
        {
            public ErrorType ErrorCode { get; set; } = ErrorType.CameraError;
            public Dictionary<int, string> Data { get; set; }

        }

        public class Result
        {
            public string barcode { get; set; }
            public bool flag { get; set; } = false;

            public QRCodeResult qRCodeResult { get; set; }

            public string message { get; set; }
        }
    }
}
